﻿using System;
using System.Windows.Forms;
using ToolkitForms;

namespace LuaVM.Helpers
{
	class HotkeyManager
	{
		public delegate void HotkeyStrokeDelegate();
		public const int EventID = 0;

		public Form Form { get; set; }
		public HotkeyData Hotkey { get; set; }
		public HotkeyStrokeDelegate HotkeyStroke { get; set; }


		public void RegisterHotkey()
		{
			if (Hotkey.Key == Keys.None)
			{
				return;
			}

			bool success = Win32API.Hotkey.RegisterHotKey(Form.Handle, EventID, Hotkey.Key, (Keys)Hotkey.Modifiers);
			if (!success)
			{
				MessageForm.Warning(Form, "注册全局热键失败：" + Hotkey.ToString(), "错误");
			}
		}

		public void UnregisterHotkey()
		{
			try
			{
				Win32API.Hotkey.UnregisterHotKey(Form.Handle, 0);
			}
			catch
			{
			}
		}

		public void ParseWndProc(ref Message m)
		{
			int id = Win32API.Hotkey.IsHotkeyEvent(ref m);
			if (id == EventID)
			{
				HotkeyStroke?.Invoke();
			}
		}

		public bool DoConfig()
		{
			HotkeyForm dlg = new HotkeyForm();
			dlg.Text = "脚本运行/停止全局热键";
			dlg.Hotkey = Hotkey;
			if (dlg.ShowDialog(Form) != DialogResult.OK)
			{
				return false;
			}

			UnregisterHotkey();
			RegisterHotkey();
			return true;
		}
	}
}
